var url = require("url");
var querystring = require("querystring");
var fs = require("fs");
var wechat_cfg = require("../wechat-cfg.json");
var wechat = require('node-wechat')(wechat_cfg.Token);
var evernote_cfg = require('../evernote-cfg.json');
var simpleEvernote = require('../lib/simpleEvernote.js')({
    token: evernote_cfg.production.token,//申请的开发者token，正式环境使用evernote_cfg.production.token,沙盒使用evernote_cfg.develop.token
    sandbox: evernote_cfg.evernoteNotUseSandbox,//是否使用沙盒，正式上线时否
    serviceHost: "app.yinxiang.com" //印象笔记中国使用app.yinxiang.com,evernote使用www.evernote.com
});

var express = require('express');
var router = express.Router();
var path = require('path');
var fetchUrl = require("fetch").fetchUrl;
var cheerio = require('cheerio');
var http = require('http');

var commentBoxMaker = function(url_str,callback) {

    //如果URL不带协议就补成http
    var URL = url.parse(url_str);
    if (URL.protocol == null){
        URL.href = 'http://'+URL.href;
    }

    //抓取URL返回的HTML，加入聊天插件，保存在工程目录views中备用
    fetchUrl(URL.href, function(error, meta, body){


        var data = body.toString();

        var document = cheerio.load(data);

        document('body').append('<link rel="stylesheet" href="stylesheets/base.css"/>'+
            '<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/react.js"></script>'+
            '<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/JSXTransformer.js"></script>'+
            '<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>'+
            '<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>'+
            '<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script>'+
            '<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>'+
            '<script type="text/jsx;harmony=true" src="scripts/chatbox.js"></script>'+
            '<div id="stargazyCommentBox"></div>');


        callback(error);

        fs.writeFile(path.join(__dirname,'../views/commentbox.html'), document.html(), function (err) {
        if (err) throw err;
        });
    });


};

//设置链式监听
wechat.text(function (data) {
    // TODO
    //免责声明 #@
    //按日期搜索 date@
    //搜索 @[text]
    //按标题搜索 title@[text]
    //设置聊天室 chat@[url]


    var words = '';
    if (data.Content.search(/title@/)  == '0' || data.Content.search(/@/)  == '0'){
        words = data.Content.search(/title@/)  == '0'? "intitle:" + data.Content.substr(6):data.Content.substr(1);



        simpleEvernote.getNotebookByName(evernote_cfg.wechatSreachNotebook, function (noteBook) {

            simpleEvernote.findNotes(words, "CREATED",noteBook.guid, function (note_list) {


                content = "搜索结果如下：\n";

                for(i=0;i<note_list.notes.length;i++){
                    content +=  i+1 + ' <a href="'+ note_list.notes[i].attributes.sourceURL +'">'+note_list.notes[i].title +'</a> \n'

                }

                var msg = {
                    FromUserName: data.ToUserName,
                    ToUserName: data.FromUserName,
                    MsgType: "text",
                    Content: content
                }

                wechat.send(msg);


            });
        })

    } else if (data.Content.search(/#@/)  == '0') {
        words = "免责声明:\n" +
            "1.原创文章会在显著位置注明原创，其他均为转载。\n" +
            "2.转载的文章，其版权均归原作者所有，如再次转载，请在转载有关文章时务必尊重该文章的版权、著作权，并自负版权等法律责任。\n"+
            "3.本人转载文章出于了解信息之目的，并不意味着赞同其观点或证实其内容的真实性。转载文章仅代表作者本人的观点，不代表本人的观点和看法，与本人立场无关，" +
            "同时本人不对其中包含或引用的信息的准确性、可靠性或完整性提供任何明示或暗示的保证。对于任何因直接或间接采用、转载本订阅号提供的信息造成的损失，本人均不承担责任\n";
        var msg = {
            FromUserName: data.ToUserName,
            ToUserName: data.FromUserName,
            MsgType: "text",
            Content: words
        }

        wechat.send(msg);

    } else if (data.Content.search(/chat@/)  == '0') {

        var url = data.Content.substr(5);
        commentBoxMaker(url,function(err){
            if (err) throw err;
            words = "http://203.195.160.134/chat";
            var msg = {
                FromUserName: data.ToUserName,
                ToUserName: data.FromUserName,
                MsgType: "text",
                Content: "聊天室已生成，网址为：" + words
            };

            wechat.send(msg);
        });


    }
    else {
        words = "留言不能保证及时回复，如有急事请直接联系我微信号\n" +
            "查看免责声明回复 #@ \n" +
            "全文搜索回复 @ \n" +
            "文本搜索回复 @[text] \n" +
            "标题搜索回复 title@[text]"+
            "设置聊天室 chat@[url]";
        var msg = {
            FromUserName: data.ToUserName,
            ToUserName: data.FromUserName,
            MsgType: "text",
            Content: words
        }

        wechat.send(msg);

    }





}).image(function (data) {
    // TODO
}).location(function (data) {
    // TODO
}).link(function (data) {
    // TODO
}).event(function (data) {
    // TODO
    if(data.Event == "subscribe"){
        words = "个人订阅号无法认证，所以不能自动推送信息。 \n" +
            "以下为使用该订阅号的正确姿势，使用前请先阅读免责声明：\n" +
            "查看免责声明回复 #@ \n" +
            "全文搜索回复 @ \n" +
            "文本搜索回复 @[text] \n" +
            "标题搜索回复 title@[text]"+
            "设置聊天室 chat@[url]";
        var msg = {
            FromUserName: data.ToUserName,
            ToUserName: data.FromUserName,
            MsgType: "text",
            Content: words
        }

        wechat.send(msg);
    }

}).voice(function (data) {
    // TODO
}).video(function (data) {
    // TODO
}).all(function (data) {

});

//响应微信接口
function wechat_response(req, res, next) {

    //校验是否是微信公众平台发来的请求
    var query = querystring.parse(url.parse(req.url).query);

    if (query.signature && query.timestamp && query.nonce) {
        //检验 token


        wechat.checkSignature(req, res);

        //预处理
        wechat.handler(req, res);



    } else {
        next();
    }

};



router.use('/',wechat_response);


module.exports = router;
